import glob from 'glob';
import ffmpeg from 'fluent-ffmpeg/lib/fluent-ffmpeg';

export type TSplitVideoOption = {
  onOutput?: (msg: string) => void;
  onFinish?: () => void;
};
export const splitVideo = async (config, option: TSplitVideoOption) => {
  const videos = await glob.sync(config.sourceDirectory + '/*.mp4');
  for (let i = 0; i < videos.length; i++) {
    await new Promise((resolve, reject) => {
      const command = ffmpeg(videos[i]);
      command.ffprobe(0, function (err, data) {
        console.log('file1 metadata:');
        console.dir(data);
        command
          .seekInput(config.startSeconds)
          .inputOption('-to ' + (data.format.duration - config.endSeconds))
          .on('start', (commandLine) => {
            console.log(commandLine);
            option?.onOutput(`[${i + 1}/${videos.length}] ` + videos[i] + ` 开始分割`);
          })
          .on('error', (err) => {
            reject(err);
          })
          .on('end', async () => {
            resolve(null);
            option?.onOutput(`[${i + 1}/${videos.length}] ` + videos[i] + ` 开始分割结束`);
            if (i === videos.length - 1) {
              option?.onFinish();
            }
          });
        const temp = videos[i].split('/');
        const filename = temp[temp.length - 1];
        command.outputOption('-c copy').save(config.targetDirectory + '/' + filename);
      });
    });
  }
};
